<template>
  <div class="expense-list-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="user-info">
        <span>欢迎光临！</span>
        <el-avatar size="small" icon="user"></el-avatar>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-panel bg-white rounded-lg shadow-sm p-4 mb-4">
      <el-form :inline="true" :model="filter" class="filter-form">
        <!-- 第一行筛选条件 -->
        <el-form-item label="供应商" label-width="80px">
          <el-select
            v-model="filter.supplier"
            placeholder="请选择供应商"
            @click="openSupplierDialog"
            readonly
            class="w-full cursor-pointer"
          >
            <el-option label="(空)" value="" />
          </el-select>
        </el-form-item>

        <el-form-item label="所有支出项目" label-width="80px">
          <el-select v-model="filter.expenseItem" class="w-full">
            <el-option label="所有支出项目" value="" />
            <el-option label="员工借款" value="loan" />
            <el-option label="手续费" value="fee" />
            <el-option label="话费补贴" value="phone" />
            <el-option label="运费" value="freight" />
            <el-option label="陈列费" value="display" />
          </el-select>
        </el-form-item>

        <el-form-item label="源单制单人" label-width="80px">
          <el-select v-model="filter.creator" class="w-full">
            <el-option label="(空)" value="" />
            <el-option label="Michael Li" value="michael" />
            <el-option label="陈宝贤" value="chen" />
            <el-option label="桂彩兰" value="gui" />
            <el-option label="销售部01" value="sales01" />
            <el-option label="lkhan002" value="lkhan" />
          </el-select>
        </el-form-item>

        <el-form-item label="源单据类型" label-width="80px">
          <el-select v-model="filter.sourceDocType" class="w-full">
            <el-option label="(空)" value="" />
            <el-option label="普通采购" value="purchase" />
            <el-option label="采购退回" value="purchase-return" />
            <el-option label="普通销售" value="sales" />
            <el-option label="销售退回" value="sales-return" />
          </el-select>
        </el-form-item>

        <!-- 第二行筛选条件 -->
        <el-form-item label="日期" label-width="80px">
          <el-date-picker
            v-model="filter.dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="付款状态" label-width="80px">
          <el-checkbox-group
            v-model="filter.paymentStatus"
            class="flex items-center"
          >
            <el-checkbox label="未付款" />
            <el-checkbox label="已付款" />
            <el-checkbox label="部分付款" />
          </el-checkbox-group>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="ml-auto">
          <el-button type="primary" @click="queryData">查询</el-button>
          <el-button @click="exportData" class="ml-2">导出</el-button>
          <el-button @click="payExpense" class="ml-2">支付费用</el-button>
          <el-tooltip
            content="提示：√ 表示这笔费用已分摊入商品购货成本"
            placement="top"
          >
            <el-icon class="ml-2 text-primary cursor-help"
              ><QuestionFilled
            /></el-icon>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-panel bg-white rounded-lg shadow-sm p-4">
      <div class="table-header flex justify-between items-center mb-4">
        <div class="flex items-center text-primary cursor-pointer">
          <el-icon><SettingFilled /></el-icon>
          <span class="ml-1">列设置</span>
        </div>
        <div class="text-sm text-gray-500">
          <span class="text-red-500">√</span> 表示这笔费用已分摊入商品购货成本
        </div>
      </div>

      <el-table
        :data="tableData"
        border
        stripe
        size="small"
        @selection-change="handleSelectionChange"
        class="expense-table"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column prop="supplier" label="供应商" min-width="120" />
        <el-table-column prop="expenseType" label="支出类别" min-width="120" />
        <el-table-column
          prop="amount"
          label="金额"
          align="right"
          min-width="100"
        >
          <template #default="scope">
            <span class="font-medium">¥{{ scope.row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="unpaid"
          label="未付费用"
          align="right"
          min-width="100"
        >
          <template #default="scope">
            <span class="font-medium">¥{{ scope.row.unpaid.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sourceDocNo" label="源单号" min-width="120" />
        <el-table-column
          prop="sourceUnit"
          label="源单往来单位"
          min-width="120"
        />
        <el-table-column
          prop="otherDocNo"
          label="其他支出单编号"
          min-width="120"
        />
        <el-table-column prop="sourceDate" label="源单日期" min-width="120" />
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column prop="paymentStatus" label="付款状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.paymentStatus)">{{
              scope.row.paymentStatus
            }}</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div
        v-if="tableData.length === 0"
        class="empty-state flex flex-col items-center justify-center py-16"
      >
        <el-image
          src="https://picsum.photos/200/150"
          alt="空状态"
          class="mb-4"
        />
        <p class="text-gray-500">暂无数据</p>
      </div>

      <!-- 分页 -->
      <div
        v-if="tableData.length > 0"
        class="flex justify-between items-center mt-4"
      >
        <div class="text-sm text-gray-500">共 {{ total }} 条数据</div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 供应商选择弹窗 -->
    <el-dialog
      title="选择供应商"
      v-model="supplierDialogVisible"
      width="800px"
      :before-close="handleCloseSupplierDialog"
    >
      <template #content>
        <div class="p-4">
          <el-form :inline="true" :model="supplierFilter" class="mb-4">
            <el-form-item label="类别">
              <el-cascader
                v-model="supplierFilter.categoryPath"
                :options="supplierCategoryOptions"
                :props="{
                  expandTrigger: 'hover',
                  value: 'value',
                  label: 'label',
                  children: 'children',
                }"
                size="small"
                class="w-48"
              />
            </el-form-item>
            <el-form-item label="查询">
              <el-input
                v-model="supplierFilter.keyword"
                placeholder="编号/名称/联系人/电话"
                size="small"
                class="w-64"
              />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="supplierFilter.showDisabled" size="small">
                显示禁用供应商
              </el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSuppliers" size="small">
                查询
              </el-button>
            </el-form-item>
          </el-form>

          <el-table
            :data="supplierList"
            border
            stripe
            @selection-change="handleSupplierSelectionChange"
            size="small"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="类别" prop="category" width="100" />
            <el-table-column label="编号" prop="code" width="120" />
            <el-table-column label="名称" prop="name" width="180" />
            <el-table-column label="联系人" prop="contact" width="100" />
            <el-table-column label="手机" prop="phone" width="120" />
            <el-table-column label="备注" prop="remark" width="150" />
          </el-table>

          <div class="flex justify-between items-center mt-4">
            <el-pagination
              @size-change="handleSupplierSizeChange"
              @current-change="handleSupplierCurrentChange"
              :current-page="supplierCurrentPage"
              :page-sizes="[10, 20, 50]"
              :page-size="supplierPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="supplierTotal"
              size="small"
            />
            <div class="flex gap-2">
              <el-button @click="supplierDialogVisible = false" size="small"
                >取消</el-button
              >
              <el-button type="primary" @click="confirmSupplier" size="small"
                >确定</el-button
              >
              <el-button type="text" @click="openAddSupplierDialog" size="small"
                >新增供应商</el-button
              >
            </div>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 新增供应商弹窗 -->
    <el-dialog
      title="新增供应商"
      v-model="addSupplierDialogVisible"
      width="800px"
      :before-close="handleCloseAddSupplierDialog"
    >
      <template #content>
        <el-form :model="newSupplier" label-width="120px" class="p-4">
          <el-form-item label="*供应商编号" prop="code">
            <el-input v-model="newSupplier.code" size="small" />
          </el-form-item>
          <el-form-item label="*供应商名称" prop="name">
            <el-input v-model="newSupplier.name" size="small" />
          </el-form-item>
          <el-form-item label="供应商类别" prop="categoryPath">
            <el-cascader
              v-model="newSupplier.categoryPath"
              :options="supplierCategoryOptions"
              :props="{
                expandTrigger: 'hover',
                value: 'value',
                label: 'label',
                children: 'children',
              }"
              size="small"
            />
          </el-form-item>
          <el-form-item label="余额日期" prop="balanceDate">
            <el-date-picker
              v-model="newSupplier.balanceDate"
              value-format="YYYY-MM-DD"
              size="small"
            />
          </el-form-item>
          <el-form-item label="期初应付款" prop="initialPayable">
            <el-input-number
              v-model="newSupplier.initialPayable"
              size="small"
              :min="0"
              step="0.01"
              precision="2"
            />
          </el-form-item>
          <el-form-item label="期初预付款" prop="initialPrepayment">
            <el-input-number
              v-model="newSupplier.initialPrepayment"
              size="small"
              :min="0"
              step="0.01"
              precision="2"
            />
          </el-form-item>
          <el-form-item label="增值税税率" prop="taxRate">
            <el-input-number
              v-model="newSupplier.taxRate"
              size="small"
              :min="0"
              :max="100"
              step="0.01"
              precision="2"
              suffix="%"
            />
          </el-form-item>

          <!-- 联系人信息 -->
          <el-form-item label="联系人信息">
            <el-table
              :data="newSupplier.contacts"
              border
              stripe
              size="small"
              class="mb-2"
            >
              <el-table-column label="联系人" prop="name" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.name" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="手机" prop="phone" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.phone" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="座机" prop="tel" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.tel" size="small" />
                </template>
              </el-table-column>
              <el-table-column
                label="QQ/微信/Email"
                prop="contactInfo"
                width="180"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.contactInfo" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="联系地址" prop="address" width="180">
                <template #default="scope">
                  <el-input v-model="scope.row.address" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="首要联系人" prop="isPrimary" width="100">
                <template #default="scope">
                  <el-checkbox v-model="scope.row.isPrimary" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="removeContact(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" size="mini" @click="addContact"
              >添加联系人</el-button
            >
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addSupplierDialogVisible = false" size="small"
            >取消</el-button
          >
          <el-button type="primary" @click="saveSupplier" size="small"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElPagination,
  ElCheckbox,
  ElCheckboxGroup,
  ElCascader,
  ElInputNumber,
  ElAvatar,
  ElImage,
  ElTag,
  ElTooltip,
  ElIcon,
  ElMessage,
} from "element-plus";
import { SettingFilled, QuestionFilled } from "@element-plus/icons-vue";

// 筛选条件
const filter = reactive({
  supplier: "",
  expenseItem: "",
  creator: "",
  sourceDocType: "",
  dateRange: ["2025-06-01", "2025-06-26"],
  paymentStatus: [],
});

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const multipleSelection = ref([]);

// 供应商选择弹窗
const supplierDialogVisible = ref(false);
const supplierFilter = reactive({
  categoryPath: [],
  keyword: "",
  showDisabled: false,
});
const supplierList = ref([
  {
    id: 1,
    category: "广东",
    code: "G00001",
    name: "商品综合批发有限公司",
    contact: "王",
    phone: "180****0000",
    remark: "",
  },
  {
    id: 2,
    category: "酒水饮料供应商",
    code: "G00002",
    name: "金小蝶食品贸易有限公司",
    contact: "管先生",
    phone: "188****7777",
    remark: "",
  },
  {
    id: 3,
    category: "食品供应商",
    code: "G00003",
    name: "广州食品批发有限公司",
    contact: "小裴",
    phone: "180****4844",
    remark: "",
  },
  {
    id: 4,
    category: "食品供应商",
    code: "G00004",
    name: "深圳食品加工有限公司",
    contact: "樊樊",
    phone: "180****5555",
    remark: "",
  },
  {
    id: 5,
    category: "广东",
    code: "G00005",
    name: "食品零售供应商",
    contact: "李先生",
    phone: "183****2312",
    remark: "",
  },
]);
const supplierTotal = ref(5);
const supplierCurrentPage = ref(1);
const supplierPageSize = ref(10);
const selectedSupplier = ref(null);

// 供应商类别数据
const supplierCategoryOptions = ref([
  {
    label: "广东",
    value: "guangdong",
    children: [
      {
        label: "海鲜供应商",
        value: "seafood",
        children: [{ label: "测试", value: "test" }],
      },
      { label: "酒水饮料供应商", value: "drinks" },
      { label: "食品供应商", value: "food" },
    ],
  },
  {
    label: "湖南",
    value: "hunan",
    children: [
      { label: "辣条供应商", value: "snack" },
      { label: "零食供应商", value: "snacks" },
    ],
  },
]);

// 新增供应商弹窗
const addSupplierDialogVisible = ref(false);
const newSupplier = reactive({
  code: "",
  name: "",
  categoryPath: [],
  balanceDate: new Date().toISOString().split("T")[0],
  initialPayable: 0,
  initialPrepayment: 0,
  taxRate: 0,
  contacts: [
    {
      name: "",
      phone: "",
      tel: "",
      contactInfo: "",
      address: "",
      isPrimary: true,
    },
  ],
});

// 初始化数据
onMounted(() => {
  // 模拟加载表格数据
  queryData();
});

// 查询表格数据
const queryData = () => {
  // 模拟API请求
  console.log("查询参数:", filter);

  // 模拟返回数据
  tableData.value = [
    {
      id: 1,
      supplier: "金小蝶食品贸易有限公司",
      expenseType: "运费",
      amount: 1500.0,
      unpaid: 0.0,
      sourceDocNo: "CG20250601001",
      sourceUnit: "金小蝶食品贸易有限公司",
      otherDocNo: "QTZC20250601001",
      sourceDate: "2025-06-01",
      remark: "采购订单号：CGD20250601001",
      paymentStatus: "已付款",
    },
    {
      id: 2,
      supplier: "广州食品批发有限公司",
      expenseType: "陈列费",
      amount: 800.0,
      unpaid: 800.0,
      sourceDocNo: "CG20250602001",
      sourceUnit: "广州食品批发有限公司",
      otherDocNo: "QTZC20250602001",
      sourceDate: "2025-06-02",
      remark: "采购订单号：CGD20250602001",
      paymentStatus: "未付款",
    },
    {
      id: 3,
      supplier: "深圳食品加工有限公司",
      expenseType: "手续费",
      amount: 50.0,
      unpaid: 0.0,
      sourceDocNo: "CG20250603001",
      sourceUnit: "深圳食品加工有限公司",
      otherDocNo: "QTZC20250603001",
      sourceDate: "2025-06-03",
      remark: "采购订单号：CGD20250603001",
      paymentStatus: "已付款",
    },
    {
      id: 4,
      supplier: "商品综合批发有限公司",
      expenseType: "员工借款",
      amount: 2000.0,
      unpaid: 1000.0,
      sourceDocNo: "CG20250604001",
      sourceUnit: "商品综合批发有限公司",
      otherDocNo: "QTZC20250604001",
      sourceDate: "2025-06-04",
      remark: "采购订单号：CGD20250604001",
      paymentStatus: "部分付款",
    },
    {
      id: 5,
      supplier: "食品零售供应商",
      expenseType: "话费补贴",
      amount: 300.0,
      unpaid: 300.0,
      sourceDocNo: "CG20250605001",
      sourceUnit: "食品零售供应商",
      otherDocNo: "QTZC20250605001",
      sourceDate: "2025-06-05",
      remark: "采购订单号：CGD20250605001",
      paymentStatus: "未付款",
    },
  ];
  total.value = tableData.value.length;
};

// 导出数据
const exportData = () => {
  ElMessage.info("导出功能已触发，正在处理数据...");
  // 实际开发中调用导出API
};

// 支付费用
const payExpense = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择需要支付的费用记录");
    return;
  }

  // 实际开发中调用支付API
  ElMessage.info(`正在支付 ${multipleSelection.value.length} 条费用记录...`);
};

// 获取付款状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case "已付款":
      return "success";
    case "未付款":
      return "danger";
    case "部分付款":
      return "warning";
    default:
      return "info";
  }
};

// 表格选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryData();
};

// 供应商选择弹窗方法
const openSupplierDialog = () => {
  supplierDialogVisible.value = true;
};

const handleCloseSupplierDialog = (done) => {
  done();
};

const searchSuppliers = () => {
  console.log("搜索供应商:", supplierFilter);
  // 实际开发中调用供应商搜索API
};

const handleSupplierSelectionChange = (val) => {
  selectedSupplier.value = val[0] || null;
};

const confirmSupplier = () => {
  if (!selectedSupplier.value) {
    ElMessage.warning("请选择供应商");
    return;
  }

  filter.supplier = selectedSupplier.value.name;
  supplierDialogVisible.value = false;
};

// 供应商分页相关
const handleSupplierSizeChange = (val) => {
  supplierPageSize.value = val;
  searchSuppliers();
};

const handleSupplierCurrentChange = (val) => {
  supplierCurrentPage.value = val;
  searchSuppliers();
};

// 新增供应商弹窗方法
const openAddSupplierDialog = () => {
  // 重置表单
  newSupplier.code = "";
  newSupplier.name = "";
  newSupplier.categoryPath = [];
  newSupplier.contacts = [
    {
      name: "",
      phone: "",
      tel: "",
      contactInfo: "",
      address: "",
      isPrimary: true,
    },
  ];

  supplierDialogVisible.value = false;
  addSupplierDialogVisible.value = true;
};

const handleCloseAddSupplierDialog = (done) => {
  done();
};

// 联系人管理
const addContact = () => {
  newSupplier.contacts.push({
    name: "",
    phone: "",
    tel: "",
    contactInfo: "",
    address: "",
    isPrimary: false,
  });
};

const removeContact = (index) => {
  if (newSupplier.contacts.length > 1) {
    newSupplier.contacts.splice(index, 1);
  } else {
    ElMessage.warning("至少保留一个联系人");
  }
};

// 保存供应商
const saveSupplier = () => {
  if (!newSupplier.code || !newSupplier.name) {
    ElMessage.warning("供应商编号和名称不能为空");
    return;
  }

  // 构建新供应商对象
  const newSupplierObj = {
    id: Date.now(),
    category:
      newSupplier.categoryPath.length > 0
        ? supplierCategoryOptions.value.find(
            (cat) => cat.value === newSupplier.categoryPath[0]
          )?.label || ""
        : "",
    code: newSupplier.code,
    name: newSupplier.name,
    contact:
      newSupplier.contacts.find((contact) => contact.isPrimary)?.name || "",
    phone:
      newSupplier.contacts.find((contact) => contact.isPrimary)?.phone || "",
    remark: "",
  };

  // 添加到供应商列表
  supplierList.value.push(newSupplierObj);
  supplierTotal.value++;

  // 关闭弹窗
  addSupplierDialogVisible.value = false;

  // 提示成功
  ElMessage.success("供应商添加成功");

  // 自动选择新添加的供应商
  selectedSupplier.value = newSupplierObj;
  filter.supplier = newSupplierObj.name;
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  background-color: #1e40af;
  color: white;
  padding: 0 20px;
  margin-bottom: 20px;
}

.logo {
  font-size: 18px;
  font-weight: bold;
}

.nav-items {
  display: flex;
  align-items: center;
}

.nav-item {
  padding: 0 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item.active {
  font-weight: bold;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  padding: 5px 15px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin-right: 10px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

.expense-table .el-table__cell {
  padding: 8px 0;
}

.empty-state {
  min-height: 300px;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>